const {
  departYearBudgetModel,
  yearBudgetModel,
  budgetCourseModel,
} = require("../models");
const translateDataToTree = require("../utils/arrayToTree");

exports.create = async (req, res, next) => {
  try {
    const addOne = new departYearBudgetModel(req.body);
    const ret = await addOne.save();
    res.status(200).json({
      data: ret,
    });
  } catch (err) {
    next(err);
  }
};
// 获取Tabel
exports.getAll = async (req, res, next) => {
  try {
    const allList = await departYearBudgetModel
      .find()
      .populate("depart", "name");
    res.status(200).json(allList);
  } catch (err) {
    next(err);
  }
};
// 获取详情列表
exports.get = async (req, res, next) => {
  try {
    const oneDepartYearBudget = await yearBudgetModel.findOne(req.query);
    // oneDepartYearBudget.targetKeysList //当年所有id
    // 根据id 查 预算科目整体
    const allDepartYearBudgetList = await budgetCourseModel.find({
      _id: { $in: oneDepartYearBudget.targetKeysList },
    });
    const result = translateDataToTree(
      JSON.parse(JSON.stringify(allDepartYearBudgetList))
    );
    res.status(200).json(result);
  } catch (err) {
    next(err);
  }
};
// 更新
exports.patch = async (req, res, next) => {
  try {
    const findAndUpdateYearBudget =
      await departYearBudgetModel.findOneAndUpdate(
        { _id: req.body.id },
        {
          $set: {
            targetKeysList: req.body.targetKeysList,
          },
        }
      );
    res.status(200).json(findAndUpdateYearBudget);
  } catch (err) {
    next(err);
  }
};
// 删除
exports.delete = async (req, res, next) => {
  try {
    const ret = await yearBudgetModel.findOneAndDelete({ _id: req.body.id });
    res.status(200).json({
      data: ret,
    });
  } catch (err) {
    next(err);
  }
};
// 详情
exports.detail = async (req, res, next) => {
  try {
    const ret = await departYearBudgetModel
      .findOne(req.query)
      .populate("targetKeysList");
    res.status(200).json(ret);
  } catch (err) {
    next(err);
  }
};
